/* eslint-disable @next/next/no-img-element */
import { GetServerSideProps } from "next";
import * as articleService from "../../services/article.service";
import * as userService from "../../services/user.service";
import { IArticle, IComment, IUser } from "../../types";
import * as React from "react";
import { useRouter } from "next/router";
import toast from "../../components/Toast";
import styles from "./article.module.scss";
import CommentItem from "../../components/commentItem";
import Header from "../../components/header";
import { Button, Input } from "antd";
import { LikeOutlined, LikeFilled } from "@ant-design/icons";
import IconFont from "../../assets/icon";
import gfm from "@bytemd/plugin-gfm";
import highlight from "@bytemd/plugin-highlight";
import "highlight.js/styles/vs.css";
import "bytemd/dist/index.min.css";
import { Viewer } from "@bytemd/react";
import { Swiper, SwiperSlide } from "swiper/react";
import SwiperCore, { Pagination, Navigation } from "swiper/core";
import "swiper/swiper-bundle.css";
import "swiper/components/pagination/pagination.min.css";
import Link from "next/link";

SwiperCore.use([Pagination, Navigation]);

const plugins = [
  gfm(),
  highlight(),
  // Add more plugins here
];

const { TextArea } = Input;

interface Props {
  article: IArticle[];
  user: IUser;
  isLiked: boolean;
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const result = await articleService.detail(ctx.query.id as string);
  await articleService.view(ctx.query.id as string);
  const user = await userService.userInfo(ctx.req.cookies.token);
  if (user.data) {
    const res = await articleService.findLike(
      ctx.query.id as string,
      ctx.req.cookies.token
    );
    return {
      props: {
        article: result.data,
        user: user.data,
        isLiked: res.result,
      },
    };
  }
  return {
    props: {
      article: result.data,
      user: null,
      isLiked: false,
    },
  };
};

export default function Article(props: Props) {
  const [content, setContent] = React.useState<string>(""); //自己评论的内容
  const [isLiked, setLike] = React.useState<boolean>(props.isLiked); //是否已赞
  const [comments, setComments] = React.useState<IComment[]>([]); //评论列表
  const [likes, setLikes] = React.useState<number>(props.article[0].likes);
  const router = useRouter();

  //发布评论
  const comment = async (content: string) => {
    const user = await userService.userInfo();
    if (user.message === "用户未登录") {
      toast("请先登录");
      router.push("/login");
    }
    if (content === "") {
      toast("请输入内容");
    } else {
      await articleService.comment(props.article[0]._id, content);
      setContent("");
      getData();
    }
  };

  const remove = async (id: string) => {
    await articleService.removeComment(id);
    getData();
    toast("删除成功");
  };

  //点赞按钮click
  const like = async () => {
    const user = await userService.userInfo();
    if (user.message === "用户未登录") {
      toast("请先登录");
      router.push("/login");
    } else {
      await articleService.like(
        props.article[0]._id,
        isLiked,
        props.article[0].title
      );
      if (isLiked === false) {
        setLikes(likes + 1);
      } else {
        setLikes(likes - 1);
      }
      setLike(!isLiked);
    }
  };

  const getData = React.useCallback(async () => {
    const comments = await articleService.comments(props.article[0]._id);
    setComments(comments.rows);
  }, [props.article]);

  React.useEffect(() => {
    getData();
  }, [getData]);
  return (
    <div className={styles.wrap}>
      <Header user={props.user} />
      {/* main */}
      <div className={styles.back}>
        <div className={styles.main}>
          <div className={styles.header}>
            <div className={styles.title}>{props.article[0].title}</div>
            <div className={styles.time}>
              文章标签：
              {props.article[0].label.map((item, index) => {
                return (
                  <span className={styles.label} key={index}>
                    {item}
                  </span>
                );
              })}
              <span className={styles.time2}>
                发布于：
                {new Date(props.article[0].time).toLocaleDateString() +
                  " " +
                  new Date(props.article[0].time).toLocaleTimeString()}
              </span>
            </div>
          </div>

          <div className={styles.author}>
            <Link href={"/user/" + props.article[0].author} passHref>
              <div
                style={{
                  height: "30px",
                  width: "30px",
                  cursor: "pointer",
                  borderRadius: "30px",
                  backgroundSize: "cover",
                  backgroundImage: `url(/api/article/download/${props.article[0].user[0].avatar})`,
                }}
              ></div>
            </Link>

            <div className={styles.nickname}>
              {props.article[0].user[0].nickname}
            </div>
          </div>
          <Swiper
            className={
              props.article[0].banner?.length === 0
                ? styles.none
                : styles.covers
            }
          >
            {props.article[0].banner?.map((item, index) => (
              <SwiperSlide key={index}>
                <img
                  src={`/api/article/download/${item}`}
                  alt=""
                  style={{
                    height: "200px",
                    backgroundSize: "cover",
                  }}
                />
              </SwiperSlide>
            ))}
          </Swiper>
          <div className={styles.content}>
            <Viewer value={props.article[0].content} plugins={plugins} />
          </div>
          <div className={styles.hot}>
            <div className={styles.view}>
              <IconFont
                className={styles.icon}
                type="icon-iconzhengli_liulan"
              />
              {props.article[0].views}
            </div>
            <div className={styles.like} onClick={like}>
              {React.createElement(
                isLiked === true ? LikeFilled : LikeOutlined
              )}
              <span className={styles.num}>{likes}</span>
            </div>
          </div>
          <div className={styles.comments}>
            {comments.map((item, index) => {
              return (
                <div className={styles.item} key={index}>
                  <CommentItem comment={item} />
                  <IconFont
                    onClick={() => remove(item._id)}
                    type="icon-icon--"
                    className={
                      props.article[0].author === item.userId ||
                      props.user?._id === item.userId
                        ? styles.icon2
                        : styles.none
                    }
                  />
                </div>
              );
            })}
          </div>
        </div>

        <div className={styles.postcomment}>
          <span className={styles.text}>评论：</span>
          <TextArea
            rows={6}
            className={styles.textarea}
            onChange={(e) => {
              setContent(e.target.value);
            }}
            value={content}
          />
          <Button
            size="large"
            className={styles.btn}
            onClick={() => comment(content)}
          >
            发布评论
          </Button>
        </div>
      </div>
    </div>
  );
}
